本篇同步發文在個人Blog: 一袋.NET要扛幾樓?打造容器化的ASP.NET Core網站!系列文章 - (28) 建立購物車系統 - 11
在網站登入後,要增加購物車Cart ViewComponent,需修改_LoginPartial.cshtml:
@using WebMvc.Services
@inject IAuthService<ApplicationUser> UserManager
@if (User?.Identity?.IsAuthenticated == true)
{
<li>
@User.FindFirst(x => x.Type == "preferred_username").Value
</li>
<li>
@await Component.InvokeAsync("Cart", new { user = UserManager.Get(User) })
</li>
<li class="pull-right">
<form asp-area="" asp-controller="Account" asp-action="SignOut" method="post" id="logoutForm">
<a href="javascript:document.getElementById('logoutForm').submit()">
Log Out
</a>
</form>
</li>
}
else
{
<li>
<a asp-area="" asp-controller="Account" asp-action="SignIn">
Login
</a>
</li>
}
在Views/Shared的目錄,新增Components目錄,再新增Cart目錄,最後加上Default.cshtml,也就是之前繼承ViewComponent的Cart.cs會回傳的頁面,主要是顯示購物車的數量:
@model WebMvc.ViewModels.CartComponentViewModel
@{
ViewData["Title"] = "My Cart";
}
<a class="@Model.Disabled" asp-area="" asp-controller="Cart" asp-action="Index">
@if (ViewBag.IsCartInoperative == true)
{
<p class="fa fa-2x fa-shopping-cart">X</p>
}
else
{
<p class="fa fa-2x fa-shopping-cart">@Model.ItemsInCart</p>
}
</a>